﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace Tensop.Net.Http
{
    public class WebConnection:IDisposable
    {
        private                 Socket      m_Socket;
        private                 string      m_Host;
        private                 bool        m_KeepAlive;
        private     static      Random      RANDOM;


        //
        //  第一次初始化的时候初始化随机数
        //

        static WebConnection()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] b = new byte[ 4 ];
            rng.GetBytes( b );
            RANDOM = new Random( BitConverter.ToInt32( b, 0 ) );
        }


        //
        // 
        //

        public WebConnection(string uri) : this( uri, false ,"GET","","","") { }


        public WebConnection(string uri,bool keepAlive,
            string Method,
            string request,
            string cookie,
            string userAgent)
        {
            m_Socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

            try
            {
                m_Host = uri;
                m_KeepAlive = keepAlive;
                var WebSiteAddresses = Dns.GetHostAddresses( uri );

                var TargetAddress = WebSiteAddresses.Length > 1 ? Random( WebSiteAddresses ) : WebSiteAddresses[ 0 ];
                Task HttpInterActive = new Task( new Action( StartHttpInterActive ) );
                HttpInterActive.Start();            
            }
            catch
            {

            }

        }

        public void Dispose()
        {
            m_Socket.Disconnect( false );
            m_Socket.Dispose();
        }

        private IPAddress Random(IPAddress[] addr)=> addr[ RANDOM.Next( 0, addr.Length - 1 ) ];


        private void StartHttpInterActive()
        {
            while(m_KeepAlive)
            {

            }
        }
    }
}
